package com.draw.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;

public class DrawLineServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.service(req, resp);
        //禁止页面缓存
        resp.setHeader("Pragma","No-cache");
        resp.setHeader("Cache-Control","No-cache");
        resp.setDateHeader("Expires",0);
        resp.setContentType("image/JPEG");//设置响应格式为JPEG图片
        //创建一个指定长度的图像
        int width = 240,height=180;
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
        Graphics graphics = image.getGraphics();//获取用于处理图形上下文的对象
        graphics.setColor(new Color(178,186,174));//设置RGB颜色
        graphics.fillRect(0,0,width,height);//填充指定的矩形
        graphics.setColor(Color.BLACK);//设置直线的颜色
        graphics.drawLine(70,50,180,50);//设置第一条直线x1,y1,x2,y2分别表示第一个点的x，y坐标和第二个点的x，y坐标
        graphics.drawLine(70,80,180,80);
        graphics.drawLine(110,10,140,120);
        graphics.dispose();//释放次图形的上下文以及它使用的所有系统资源
        ImageIO.write(image,"JPEG",resp.getOutputStream());//输出JPEG格式图片到页面
        resp.getOutputStream().flush();//刷新输出流
        resp.getOutputStream().close();//关闭输出流
    }
}
